package com.example.demo.service;

import com.example.demo.entity.Excel;
import com.example.demo.mapper.ExcelMapper;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.SimpleTimeZone;

@Service
public class ExcelServiceImpl implements ExcelService {
    @Autowired
    private ExcelMapper excelMapper;

    @Override
    public void exprotExcel(HttpServletResponse response) throws IOException {
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        HSSFSheet hssfSheet = hssfWorkbook.createSheet("test");
        HSSFRow hssfRow = hssfSheet.createRow(0);
        HSSFCellStyle hssfCellStyle = hssfWorkbook.createCellStyle();
        hssfCellStyle.setAlignment(HorizontalAlignment.CENTER);

        HSSFCell hssfCell = hssfRow.createCell(0);
        hssfCell.setCellValue("ID");
        hssfCell.setCellStyle(hssfCellStyle);

        hssfCell = hssfRow.createCell(1);
        hssfCell.setCellValue("姓名");
        hssfCell.setCellStyle(hssfCellStyle);

        hssfCell = hssfRow.createCell(2);
        hssfCell.setCellValue("性别");
        hssfCell.setCellStyle(hssfCellStyle);

        hssfCell = hssfRow.createCell(3);
        hssfCell.setCellValue("年龄");
        hssfCell.setCellStyle(hssfCellStyle);

        List<Excel> excelList = excelMapper.getAllUser();

        for (int i = 0; i < excelList.size(); i++) {
            hssfRow = hssfSheet.createRow(i + 1);
            Excel excel = excelList.get(i);
            hssfRow.createCell(0).setCellValue(excel.getId());
            hssfRow.createCell(1).setCellValue(excel.getName());
            hssfRow.createCell(2).setCellValue(excel.getSex());
            hssfRow.createCell(3).setCellValue(excel.getAge());
        }

        OutputStream outputStream = response.getOutputStream();
        response.reset();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = simpleDateFormat.format(new Date());
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
        response.setContentType("application/msexcel");
        hssfWorkbook.write(outputStream);
        outputStream.close();
    }


}
